package xyz.xtt.equity.mq;

import static xyz.xtt.common.asset.AssertUtils.isNull;

import java.nio.charset.StandardCharsets;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.equity.constants.ErrorMessage;
import xyz.xtt.equity.service.INftVipService;
import xyz.xtt.pay.api.dto.BusinessOrderStatusChangeMsg;

/**
 * @author dale
 * @date 2025/3/17
 **/
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.business.order.status.change.topic:nft_pay_business_order_status_change_topic}", selectorExpression = "nft_vip_month_pay_success||nft_vip_season_pay_success||nft_vip_year_pay_success", consumerGroup = "${rocketmq.consumer.group.exchange.benefit.order.pay.success:nft_exchange_benefit_order_pay_success_group}")
public class BenefitBusinessOrderPayStatusChangeConsumer implements RocketMQListener<MessageExt> {
	@Autowired
	private INftVipService nftVipService;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		byte[] body = msg.getBody();
		String message = new String(body, StandardCharsets.UTF_8);
		log.info("BenefitBusinessOrderPayStatusChangeConsumer msgId:{} message: {}", msgId, message);
		if (StringUtils.isEmpty(message)) {
			return;
		}
		if (!JSONUtil.isTypeJSON(message)) {
			log.warn("BenefitBusinessOrderPayStatusChangeConsumer Received message: {} is not json", message);
			return;
		}

		BusinessOrderStatusChangeMsg statusChangeMsg = JSONUtil.toBean(message, BusinessOrderStatusChangeMsg.class);
		isNull(statusChangeMsg, ErrorMessage.ARGUMENT_NOT_VALID);
		log.info("BenefitBusinessOrderPayStatusChangeConsumer statusChangeMsg: {}", message);
		nftVipService.handlePaySuccess(statusChangeMsg.getBusinessOrderId());
	}
}
